package com.ly.erms.core.aop;

import java.lang.reflect.Method;

import javax.naming.NoPermissionException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.ly.erms.common.annotion.Permission;
import com.ly.erms.core.shiro.check.PermissionCheckManager;

/**
 * AOP权限自定义检查
 * @author liuyang
 * @date 2018年1月8日
 */
@Component
@Aspect
public class PermissionAop {
	
	@Pointcut(value="@annotation(com.ly.erms.common.annotion.Permission)")
	private void cutPermission(){
	}
	
	@Around("cutPermission()")
	public Object doPermission(ProceedingJoinPoint point) throws Throwable{
		MethodSignature ms = (MethodSignature)point.getSignature();
		Method method = ms.getMethod();
		Permission permission = method.getAnnotation(Permission.class);
		String[] permissions = permission.value();
		if(permissions ==null || permissions.length==0){
			//检查全体角色
			boolean result = PermissionCheckManager.checkAll();
			if(result){
				return point.proceed();
			}else{
				throw new NoPermissionException();
			}
		}else{
			//检查指定角色
			boolean check = PermissionCheckManager.check(permissions);
			if(check){
				return point.proceed();
			}else{
				throw new NoPermissionException();
			}
		}
	}
}
